package com.wy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wy.common.Result;
import com.wy.entity.GoodsEvaluation;
import com.wy.entity.UserInfo;
import com.wy.service.GoodsEvaluationService;
import com.wy.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * @Author:王渝
 * @Date: 2022/11/30  11:25
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private GoodsEvaluationService goodsEvaluationService;

    @Value("${file.url}")
    private String url;
    /**
     * 用户注册
     * @param userInfo 用户信息
     * @return
     */
    @RequestMapping("/register")
    public Result<UserInfo> register(@RequestBody UserInfo userInfo){
        if(userInfo == null){
            return Result.error("用户信息为空");
        }
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserName,userInfo.getUserName());
        //select * from user_info where user_name = ?
        //查询用户名是否已经注册
        UserInfo user = userInfoService.getOne(queryWrapper);
        if(user != null){
            return Result.error("用户名已存在");
        }
        //注册
        Boolean register = userInfoService.register(userInfo);
        if(!register){
            return Result.error("注册失败");
        }
        return Result.success(null);
    }

    /**
     * 用户登录
     * @param userInfo
     * @return
     */
    @RequestMapping("/login")
    public Result<UserInfo> login(@RequestBody UserInfo userInfo, HttpSession session){
        if(userInfo == null){
            return Result.error("请输入用户名和密码");
        }
        //验证验证码
        if(!session.getAttribute("loginCode").equals(userInfo.getCode())){
            return Result.error("验证码错误");
        }
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(UserInfo::getUserName,UserInfo::getUserId,
                            UserInfo::getStatus,
                            UserInfo::getPhone,
                            UserInfo::getEmail,
                            UserInfo::getBalance,
                            UserInfo::getHeadImage);
        queryWrapper.eq(UserInfo::getPassword,DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()))
                .eq(UserInfo::getUserName,userInfo.getUserName());
        //select user_id,user_name,status,phone,email,balance,head_image from user_info where user_name = ? password = ?
        UserInfo user = userInfoService.getOne(queryWrapper);
        if(user == null){
            return Result.error("用户名或密码错误");
        }
        if(Objects.equals(user.getStatus(), "2")){
            return Result.error("账号异常");
        }
        user.setHeadImage(url+user.getHeadImage());
        //将用户信息存入session
        session.setAttribute("userId",user.getUserId());
        return Result.success(user);
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public Result<String> logout( HttpSession session){
        session.removeAttribute("userId");
        return Result.success("退出登录");
    }

    /**
     * 根据用户id查询用户信息
     * @param userId
     * @return
     */
    @RequestMapping("/getUserInfo/{userId}")
    public Result<UserInfo> getUserInfo(@PathVariable Long userId,HttpSession session){
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(UserInfo::getUserId,
                UserInfo::getUserName,
                UserInfo::getHeadImage,
                UserInfo::getBalance,
                UserInfo::getEmail);
        lambdaQueryWrapper.eq(UserInfo::getUserId,userId);
        //select user_name ,head_Image,balance,email form user_info where user_id = ?
        UserInfo user = userInfoService.getOne(lambdaQueryWrapper);
        user.setHeadImage(url + user.getHeadImage());
        session.setAttribute("userId",user.getUserId());
        return Result.success(user);
    }

    /**
     * 根据id查询卖方用户信息
     * @param goodsId 用户id
     * @return
     */
    @RequestMapping("/getSeller/{goodsId}")
    public Result<UserInfo> getSellerInfo(@PathVariable Long goodsId){

        //查询平均评价
        BigDecimal avgRate = goodsEvaluationService.getAvgRateBySellerGoodsId(goodsId);
        //查新卖方基本信息
        UserInfo one = userInfoService.queryUserInfoByGoodsId(goodsId);
        one.setAvgRate(avgRate);
        one.setHeadImage(url+one.getHeadImage());
        return Result.success(one);
    }

    /**
     * 根据id查询卖方用户信息
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/getSeller2/{userId}")
    public Result<UserInfo> getSellerInfo2(@PathVariable Long userId){

        //查询平均评价
        BigDecimal avgRate = goodsEvaluationService.getAvgRateBySellerUserId(userId);
        //查新卖方基本信息
        UserInfo one = userInfoService.queryUserInfoByUserId(userId);
        one.setAvgRate(avgRate);
        one.setHeadImage(url+one.getHeadImage());
        return Result.success(one);
    }

    /**
     * 修改头像
     * @param userInfo 用户信息
     * @return
     */
    @RequestMapping("/changeHead")
    public Result<String> changeHeadImage(@RequestBody UserInfo userInfo){
        log.info("{}",userInfo);
        String headImage = userInfo.getHeadImage();
        String[] split = headImage.split("=");
        String image = split[1];
        LambdaUpdateWrapper<UserInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(UserInfo::getHeadImage,image);
        lambdaUpdateWrapper.eq(UserInfo::getUserId,userInfo.getUserId());

        boolean update = userInfoService.update(lambdaUpdateWrapper);
        if(update){
            return Result.success("更新成功");
        }
        return Result.error("上传失败");
    }


    /**
     * 根据用户id查询用户头像
     * @param userId
     * @return
     */
    @RequestMapping("/getUserHeadImage/{userId}")
    public Result<String> getUserHeadImage(@PathVariable Long userId){
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(UserInfo::getUserId,
                UserInfo::getHeadImage);
        lambdaQueryWrapper.eq(UserInfo::getUserId,userId);
        UserInfo user = userInfoService.getOne(lambdaQueryWrapper);
        return Result.success(url + user.getHeadImage());
    }

    /**
     * 修改邮箱
     * @param userInfo 用户信息
     * @return
     */
    @RequestMapping("/changeEmail")
    public Result<String> changeEmail(@RequestBody UserInfo userInfo){
        LambdaUpdateWrapper<UserInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(UserInfo::getEmail,userInfo.getEmail());
        lambdaUpdateWrapper.eq(UserInfo::getUserId,userInfo.getUserId());

        boolean update = userInfoService.update(lambdaUpdateWrapper);
        if(update){
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    /**
     * 禁用用户
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/forbidden/{userId}")
    public Result<String> forbiddenUser(@PathVariable Long userId){
        LambdaUpdateWrapper<UserInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        lambdaUpdateWrapper.eq(UserInfo::getUserId,userId).set(UserInfo::getStatus,2);
        boolean isSuccess = userInfoService.update(lambdaUpdateWrapper);
        if(isSuccess){
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }




    /**
     * 查询用户信息用户
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/query/{userId}")
    public Result<UserInfo> queryUserInfo(@PathVariable Long userId){
        //查询平均评价
        BigDecimal avgRate = goodsEvaluationService.getAvgRateBySellerUserId(userId);
        //查新用户全部信息
        UserInfo one = userInfoService.getById(userId);
        one.setAvgRate(avgRate);
        one.setHeadImage(url+one.getHeadImage());
        return Result.success(one);
    }


    /**
     * 修改密码
     * @param userInfo 用户信息
     * @return
     */
    @RequestMapping("/changePassword")
    public Result<String> changePassword(@RequestBody UserInfo userInfo){
        LambdaUpdateWrapper<UserInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserInfo::getUserName,userInfo.getUserName())
                .set(UserInfo::getPassword,DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()));
        boolean isSuccess = userInfoService.update(lambdaUpdateWrapper);
        if(isSuccess){
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    /**
     * 根据用户名查询邮箱
     * @param userName 用户名
     * @return
     */
    @RequestMapping("/queryEmail/{userName}")
    public Result<UserInfo> queryUserInfo(@PathVariable String userName){
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserName,userName);
        queryWrapper.select(UserInfo::getEmail);
        UserInfo one = userInfoService.getOne(queryWrapper);
        if(one == null){
            return Result.error("用户不存在");
        }
        return Result.success(one);
    }







}
